#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_reader.h"

char* init_shm() {
    int shm_id = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);
    if (shm_id == -1) {
        perror("shmget failed");
        exit(EXIT_FAILURE);
    }

     char* shm_ptr = shmat(shm_id, NULL, 0);
    if (shm_ptr == (void*)-1) {
        perror("shmat failed");
        return NULL;
    }
    return shm_ptr;
}

char* read_shm_data(char* shm_ptr) {
    //char* shm_ptr = shmat(shm_id, NULL, 0);
    //if (shm_ptr == (void*)-1) {
    //    perror("shmat failed");
    //    return NULL;
    //}
    
    // 复制数据（防止原始数据被修改）
    char* data = strdup((char*)shm_ptr);
    //shmdt(shm_ptr);
    return data;
}

void cleanup_shm(int shm_id, void* shm_ptr) {
    shmdt(shm_ptr);
    shmctl(shm_id, IPC_RMID, NULL);
}